<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
    <script>
        class _Lazyman {
            constructor (name) {
                this.task = [];
                this.eat = this.eat.bind(this);
                this.sleep = this.sleep.bind(this);
                this.sleepFirst = this.sleepFirst.bind(this);

                this.task.push(() => {
                    console.log(`Hello, ${name}!`);
                    this.next();
                });

                setTimeout(() => this.next(), 0);
            }

            next () {
                let fn = this.task.shift();
                fn && fn();
            }

            eat (type) {
                this.task.push(() => {
                    console.log(`Eat ${type}!`);
                    this.next();
                });
                return this;
            }

            sleep (time) {
                this.task.push(() => {
                    console.log('Begin sleep...');
                    setTimeout(() => {
                        console.log(`Sleep after ${time}s`);
                        this.next();
                    }, time * 1000);
                });
                return this;
            }

            sleepFirst (time) {
                this.task.splice(1, 0, () => {
                    console.log('Begin first sleep...');
                    setTimeout(() => {
                        console.log(`Sleep after ${time}s`);
                        this.next();
                    }, time * 1000);
                });
                return this;
            }
        }

        let Lazyman = name => new _Lazyman(name);

        // Lazyman('Hank').sleep(2).eat('dinner').sleep(3).eat('supper');
        Lazyman('Tom').eat('dinner').sleepFirst(1).sleep(5).eat('supper');

    </script>
</body>
</html>